package com.yc.javaee.tomcat.impl;

import com.yc.javaee.Tomcat服务器;
import com.yc.javaee.tomcat.Cookie;
import com.yc.javaee.tomcat.HttpServletRequest;
import com.yc.javaee.tomcat.HttpSession;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.LinkedHashMap;
import java.util.Map;

public class HttpServletRequestImpl implements HttpServletRequest {
    private String method;
    private String requestURI;
    private String protocol;
    private Map<String, String> headers = new LinkedHashMap<>();
    private Map<String, String> paramters = new LinkedHashMap<>();
    public HttpServletRequestImpl(Socket socket) throws IOException {
        InputStream in = socket.getInputStream();

        byte[] bytes = new byte[4096];
        int count;
        count = in.read(bytes);
        if(count == -1){
            return;
        }
        String text = new String(bytes, 0, count);
        System.out.println(text);

        String[] lines = text.split("\r\n");
        // 记录当前处理的行是头域还实体
        boolean isHead = true;
        for (int i = 0; i < lines.length; i++) {
            if(i==0){
                // 头行
                String[] items = lines[i].split("\\s");
                method = items[0];
                requestURI = items[1];
                protocol = items[2];
                // 解析GET请求参数
                if (requestURI.contains("?")) {
                    // 127.0.0.1/a.html?a=1&b=c&c=100
                    String paramString = requestURI.substring(requestURI.indexOf("?") + 1);
                    for (String nameAndValue : paramString.split("&")) {
                        String[] nav = nameAndValue.split("=");
                        if(nav.length>1){
                            paramters.put(nav[0],nav[1]);
                        }
                    }
                    // 带参数的 GET 请求地址 要去除参数字符串
                    requestURI = requestURI.substring(0, requestURI.indexOf("?"));
                }
            } else if (lines[i].isEmpty()){
                // CRLF 空行 头域与实体的分割行
                isHead = false;
            } else if (isHead){
                // 头域
                String[] items = lines[i].split(":\\s");
                headers.put(items[0],items[1]);
            } else {
                // 实体
                System.out.println(lines);
            }
        }
        System.out.println("请求解析完成: ");
        System.out.println(this);
    }

    @Override
    public String toString() {
        return "HttpServletRequestImpl{" +
                "method='" + method + '\'' +
                ", requestURI='" + requestURI + '\'' +
                ", protocol='" + protocol + '\'' +
                ", headers=" + headers +
                '}';
    }

    @Override
    public InputStream getInputStream() {
        return null;
    }

    @Override
    public String getMethod() {
        return method;
    }

    @Override
    public String getRequestURI() {
        return requestURI;
    }

    @Override
    public String getProtocol() {
        return protocol;
    }

    @Override
    public String getHeader(String name) {
        return headers.get(name);
    }

    @Override
    public Cookie[] getCookies() {
        // 解析请求中的cookie数据
        // Cookie: $Version=1; Skin=new;
        String cookieStr = headers.get("Cookie");
        if(cookieStr != null){
            String[] nvs = cookieStr.split(";\\s?");
            Cookie[] cookies = new Cookie[nvs.length];
            for (int i = 0; i < nvs.length; i++) {
                String[] nameAndValue = nvs[i].split("=");
                Cookie cookie = new CookieImpl(nameAndValue[0],nameAndValue[1]);
                cookies[i] = cookie;
            }
            return cookies;
        } else {
            return null;
        }
    }

    @Override
    public String getRequestedSessionId() {
        Cookie[] cookies = this.getCookies();
        String sessionId = null;
        if(cookies!=null){
            for (Cookie cookie : cookies) {
                // JSEESIONID 固定的会话id保存在cookie中的名字
                if("JSESSIONID".equals(cookie.getName())){
                    sessionId = cookie.getValue();
                    break;
                }
            }
        }
        return sessionId;
    }

    private HttpSession httpSession;
    @Override
    public HttpSession getSession() {
        // getRequestedSessionId() 无值 ==> 是第一访问, 创建会话
        // getRequestedSessionId() 有值 ==> 不是第一访问, 会话容器中找到了对应会话
        // getRequestedSessionId() 有值 ==> 会话容器中找不到对应会话
        if(httpSession!=null) return httpSession;
        httpSession = Tomcat服务器.sessionMap.get(getRequestedSessionId());
        if(httpSession==null){
            httpSession = new HttpSessionImpl();
            // 将会话对象存入到容器中
            Tomcat服务器.sessionMap.put(httpSession.getId(), httpSession);
        }
        return httpSession;
    }

    @Override
    public String getParameter(String name) {
        return paramters.get(name);
    }

    @Override
    public String[] getParameterValues(String name) {
        return new String[0];
    }

    @Override
    public String getQueryString() {
        return null;
    }

    /**
     * 方法名写错, 应该是 setSession
     * 该方法不是官方 API 方法
     * @param session
     */
    @Override
    public void getSession(HttpSession session) {

    }
}
